<template>
  <div class="subtitle">
    <header>
      <div>
        <div class="title">
          字幕编辑【{{meetingBaseInfo.title}}】
        </div>
        <div class="time">
          {{meetingBaseInfo.actuallyStartTime}}
          -
          {{meetingBaseInfo.actuallyEndTime}}
        </div>
      </div>
      <div
        class="el-icon-back back"
        @click="goBack"
      >
        返回
      </div>
    </header>
    <div class="subtitles">
      <div class="left perfect-scrollbar">
        <el-table
          ref="singleTable"
          :data="tracks"
          stripe
          highlight-current-row
          style="width: 100%"
        >
          <el-table-column
            type="index"
            width="40"
            align="center"
          >
          </el-table-column>
          <el-table-column
            label="开始时间"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <template v-if="isEdit && currentRow == scope.$index">
                <el-input
                  size="mini"
                  v-model="scope.row.startTime"
                />
              </template>
              <template v-else>
                {{scope.row.startTime}}
              </template>
            </template>
          </el-table-column>
          <el-table-column
            label="结束时间"
            width="150"
            align="center"
          >
            <template slot-scope="scope">
              <template v-if="isEdit && currentRow == scope.$index">
                <el-input
                  size="mini"
                  v-model="scope.row.endTime"
                />
              </template>
              <template v-else>
                {{scope.row.endTime}}
              </template>
            </template>
          </el-table-column>
          <el-table-column
            label="字幕内容"
            align="center"
          >
            <template slot-scope="scope">
              <template v-if="isEdit && currentRow == scope.$index">
                <el-input
                  size="mini"
                  v-model="scope.row.content"
                />
              </template>
              <template v-else>
                {{scope.row.content}}
              </template>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-check"
                circle
                v-if="isEdit && currentRow == scope.$index"
                @click="handleSubmit(scope.$index, scope.row)"
              ></el-button>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                circle
                v-else
                @click="handleEdit(scope.$index, scope.row)"
              ></el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                circle
                @click="handleDelete(scope.$index, scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="right">
        <div class="videoBox">
          <video-player
            v-if="videoShow"
            class="video video-player vjs-custom-skin"
            ref="videoPlayer"
            :playsinline="true"
            :options="playerOptions"
            @timeupdate="handleTimeUpdate"
          ></video-player>
          <div
            v-else
            class="video"
          >
            无视频回放
          </div>
          <div class="track border-text">
            {{ track.content }}
          </div>
        </div>
        <div class="add">
          <el-input
            class="ipt"
            placeholder="请设置要插入的索引，默认插在结尾"
            v-model="subtitleIndex"
          />
          <el-button @click="handleAdd">
            添加字幕
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  binarySearchTrack,
  checkTrackTime,
  formatTrackTime,
  getTrackTime
} from '@/utils/track'
import { conferencesInfo } from '@/api/conferences'
import { getSubtitle } from '@/api/track'
export default {
  name: 'SubtitlesEdit',
  data () {
    return {
      videoShow: false,
      conferenceId: '',
      meetingInfo: {
        conferenceBase: {
          cid: '',
          createTime: '',
          estimatedDuration: '',
          estimatedStartTime: '',
          founderId: 0,
          Abstract: '',
          meetingNumber: '',
          password: '',
          requiredPassword: false,
          requiredSubtitle: false,
          speakLang: '',
          status: 1,
          title: '',
          translateLang: '',
          videoCoverPath: null,
          videoPath: ''
        },
        members: []
      },
      // 是否处于编辑模式
      isEdit: false,
      // 当前行
      currentRow: '',
      // 字幕信息
      track: {
        content: '字幕技术由【沧月流星】提供支持'
      },
      tracks: [],
      updateSign: false,
      subtitleIndex: '',
      // 播放器配置
      playerOptions: {
        playbackRates: [0.7, 1.0, 1.5, 2.0], // 播放速度
        autoplay: false, // 如果true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 导致视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [
          {
            type: '', // 这里的种类支持很多种：基本视频格式、直播、流媒体等，具体可以参看git网址项目
            src: '' // url地址
          }
        ],
        // poster: '../../static/images/test.jpg', // 你的封面地址
        // width: document.documentElement.clientWidth, //播放器宽度
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true,
          durationDisplay: true,
          remainingTimeDisplay: false,
          fullscreenToggle: true // 全屏按钮
        }
      }
    }
  },
  computed: {
    meetingBaseInfo () {
      return this.meetingInfo.conferenceBase
    }
  },
  watch: {
    meetingBaseInfo: {
      immediate: true,
      handler (newVal) {
        if (newVal.videoPath) {
          this.playerOptions.sources[0].src = newVal.videoPath
          this.videoShow = true
        } else {
          this.videoShow = false
        }
      }
    }
  },
  created () {
    this.conferenceId = this.$route.query.conferenceId
  },
  mounted () {
    this.conferencesInfoInit()
    this.handleGetSubtitle()
  },
  methods: {
    goBack () {
      this.$router.push({
        path: '/meetinginfo',
        query: {
          conferenceId: this.$route.query.conferenceId
        }
      })
    },
    // 获取会议信息
    async conferencesInfoInit () {
      const { data } = await conferencesInfo(this.conferenceId)
      this.meetingInfo = data
    },
    // 获取字幕
    async handleGetSubtitle () {
      const { data } = await getSubtitle(this.conferenceId)
      if (data) {
        this.tracks = data
      }
    },
    // 更新字幕
    handleTimeUpdate (e) {
      const targetTime = formatTrackTime(e.currentTime())
      const idx = binarySearchTrack(this.tracks, targetTime)
      if (idx === -1) {
        this.track = {
          content: ''
        }
      } else {
        this.track = this.tracks[idx]
      }
    },
    // 编辑字幕
    handleUpdateSubtitle (id, startTime, endTime, content) {
      this.$request.conference.updateSubtitle(
        this.conferenceId,
        id,
        startTime,
        endTime,
        content,
        res => {
          // 重新获取字幕
          this.handleGetSubtitle()
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    },
    // 点击编辑
    handleEdit (index, row) {
      this.isEdit = true
      this.currentRow = index
    },
    // 确定修改
    handleSubmit (index, row) {
      if (
        checkTrackTime(row.startTime) &&
        checkTrackTime(row.endTime) &&
        row.endTime > row.startTime &&
        (index === 0 || row.startTime >= this.tracks[index - 1].endTime) &&
        (index === this.tracks.length - 1 ||
          row.endTime <= this.tracks[index + 1].startTime)
      ) {
        this.handleUpdateSubtitle(
          row.id,
          row.startTime,
          row.endTime,
          row.content
        )
        this.isEdit = false
      }
    },
    // 删除一条字幕
    handleDeleteSubtitle (id) {
      this.$request.conference.deleteSubtitle(
        this.conferenceId,
        id,
        res => {
          // 重新获取字幕
          this.handleGetSubtitle()
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    },
    // 删除
    handleDelete (index, row) {
      this.handleDeleteSubtitle(row.id)
      this.tracks.splice(index, 1)
    },
    // 新增一条字幕
    handleAddSubtitle (startTime, endTime, content) {
      this.$request.conference.addSubtitle(
        this.conferenceId,
        startTime,
        endTime,
        content,
        res => {
          // 重新获取字幕
          this.handleGetSubtitle()
        },
        err => {
          this.$message.error(err.msg)
        }
      )
    },
    // 添加字幕
    handleAdd () {
      if (this.subtitleIndex) {
        const realIndex = this.subtitleIndex - 1
        if (realIndex < 0 || realIndex > this.tracks.length) {
          this.$message.error('索引有误')
          return
        }
        const startTime =
          realIndex === 0
            ? 0
            : getTrackTime(this.tracks[realIndex - 1].endTime)
        const endTime =
          realIndex === this.tracks.length
            ? startTime + 1
            : getTrackTime(this.tracks[realIndex].startTime)
        this.handleAddSubtitle(
          formatTrackTime(startTime),
          formatTrackTime(endTime),
          '自定义字幕内容'
        )
        this.tracks.splice(realIndex, 0, {
          startTime: formatTrackTime(startTime),
          endTime: formatTrackTime(endTime),
          content: '自定义字幕内容'
        })
      } else {
        const track = this.tracks[this.tracks.length - 1]
        this.handleAddSubtitle(
          formatTrackTime(
            getTrackTime(track.endTime) + 1
          ),
          formatTrackTime(
            getTrackTime(track.endTime) + 2
          ),
          '自定义字幕内容'
        )
        this.tracks.push({
          startTime: formatTrackTime(
            getTrackTime(track.endTime) + 1
          ),
          endTime: formatTrackTime(
            getTrackTime(track.endTime) + 2
          ),
          content: '自定义字幕内容'
        })
      }
      this.subtitleIndex = ''
    }
  }
}
</script>

<style lang="scss" scoped>
.subtitle {
  display: flex;
  height: 100%;
  flex-direction: column;
  background-color: $white;
  header {
    flex: 0 0 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    box-shadow: $shadow;
    margin-bottom: 5px;
    padding-left: 20px;
    .title {
      font-size: 18px;
      margin-bottom: 10px;
      font-weight: bold;
    }
    .time {
      font-size: 14px;
      color: #999;
    }
    .back {
      font-size: 18px;
      font-weight: bold;
      padding-right: 20px;
      cursor: pointer;
    }
  }
  .subtitles {
    flex: 1;
    display: flex;
    min-width: 1200px;
    overflow: hidden;
    .left {
      flex: 4;
      height: 100%;
      overflow-y: scroll;
    }
    .right {
      border-left: 1px solid #999;
      flex: 5;
      background-color: #ddd;
      .videoBox {
        width: 100%;
        position: relative;
        display: flex;
        justify-content: center;
        .video {
          width: 100%;
          min-height: 500px;
          display: flex;
          justify-content: center;
          align-items: center;
          max-height: 600px;
          object-fit: contain;
          background-color: #ccc;
        }
        .track {
          width: 80%;
          text-align: center;
          position: absolute;
          font-size: 25px;
          bottom: 30px;
          font-family: 'Raleway', sans-serif;
          color: $red;
        }
      }
      .add {
        display: flex;
        .ipt {
          width: 300px;
        }
      }
    }
  }
}
</style>
